<template>
  <a-row :gutter="20" flex-1>
    <a-col :span="12" class="flex flex-col">
      <div flex items-center>
        <h3 flex-auto>SQL生成</h3>
        <a-space>
          <a-button
            :icon="h(DownloadOutlined)"
            @click="download_file('DataGrid', genExcel)"
            >下载Excel</a-button
          >
          <a-upload
            name="file"
            :file-list="excel_file_list"
            :before-upload="before_upload"
            :maxCount="1"
            :show-upload-list="false"
          >
            <a-button
              :icon="h(UploadOutlined)"
              :disabled="uploading || is_finished"
              >上传Excel</a-button
            >
          </a-upload>
          <a-button
            :icon="h(RocketOutlined)"
            type="primary"
            @click="genSql"
            :disabled="genLoading"
            >生成SQL</a-button
          >
        </a-space>
      </div>
      <div flex-1 rounded-md overflow-hidden>
        <MonacoEditor
          editorId="sqlGenerationEditor"
          :model-value="genLoading ? '生成中...' : script_code"
        />
      </div>
    </a-col>
    <a-col :span="12" class="flex flex-col">
      <div flex items-center>
        <h3 flex-auto>执行结果</h3>
        <a-space>
          <a-button
            :icon="h(RocketOutlined)"
            type="primary"
            @click="execute"
            :disabled="sqlLoaindg || !script_code"
            >执行SQL</a-button
          >
        </a-space>
      </div>
      <div flex-1 rounded-md overflow-hidden>
        <MonacoEditor
          editorId="result"
          :model-value="sqlLoaindg ? '生成中...' : result"
        />
      </div>
    </a-col>
  </a-row>
  <div text-center mt-4>
    <a-space>
      <a-button type="primary" @click="$emit('goPrev')">上一步</a-button>
      <a-button type="primary" :disabled="result != '执行成功'" @click="finish">
        完成
      </a-button>
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { Modal } from 'ant-design-vue';
import { JobStep, ProcessType } from '../Step';
import { SqlData } from '../type';
import {
  DownloadOutlined,
  UploadOutlined,
  RocketOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons-vue';
import { createVNode } from 'vue';
import { uploadFile } from '@/api/global';
import { process_update } from '@/api/process';
import { Category } from '@/types/category';
import MonacoEditor from '@/components/commons/MonacoEditor.vue';
const props = defineProps<{
  stepData: JobStep;
}>();
const emits = defineEmits<{
  update: [data: unknown, processName: ProcessType];
  goPrev: [];
}>();

const { stepData } = toRefs(props);
const sqlData = ref(cloneDeep(stepData.value.data) as SqlData);

const genExcel = computed(() => sqlData.value.genExcel);

const download_file = (prefix: string, file_url: string) => {
  // 生成文件名 ${prefix}_2021-08-11_16-00-00.xlsx
  let file_name = `${prefix}_${new Date().toLocaleDateString()}_${new Date().toLocaleTimeString()}.xlsx`;
  let a = document.createElement('a');
  a.href = file_url;
  a.download = file_name;
  a.click();
};

const uploading = ref(false);
const is_finished = ref(false);
const excel_file_list = ref([]);
const script_code = ref('');

const genLoading = ref(false);
const sqlLoaindg = ref(false);

const before_upload = async file => {
  Modal.confirm({
    title: '是否上传替代当前 Excel ？',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      'div',
      { style: 'color:red;' },
      '上传后将替代当前 Excel 文件参与 SQL 生成, 请确保上传的 Excel 文件格式与内容正确!'
    ),
    async onOk() {
      uploading.value = true;
      // @ts-ignore
      excel_file_list.value = [...(excel_file_list.value || []), file];
      console.log('excel_file_list ->', excel_file_list.value);

      // 上传文件
      try {
        const upload_res = await uploadFile(file, 'CategoryExcel');
        console.log('upload_res ->', upload_res);
        sqlData.value.uploadExcel = upload_res.data;
        message.success('上传成功');
      } catch (err) {
        message.error('上传文件时发生错误');
        console.error('upload file error ->', err);
      }
      uploading.value = false;
    },
    onCancel() {
      console.log('Modal Canceled');
    },
    class: 'test',
  });
  return false;
};

const genSql = async () => {
  genLoading.value = true;
  result.value = '';
  stepData.value.updateStep('SQL_GEN', sqlData.value);
  const { id: categoryId } = st.get('_category') as Category;
  const step = stepData.value.getStep('START')!;
  try {
    const res = await process_update({
      cid: categoryId,
      data: step.format(),
      jobStep: 'SQL_GEN',
      excelUrl: sqlData.value.uploadExcel || sqlData.value.genExcel,
    });
    if (res.code == 'ok') {
      script_code.value = (res.data as any).data as string;
    } else {
      message.error(res.message);
    }
  } catch (error) {
    console.log('%c Line:127 🍖 error', 'color:#2eafb0', error);
  }
  genLoading.value = false;
};

const result = ref('');
const execute = async () => {
  sqlLoaindg.value = true;
  const { id: categoryId } = st.get('_category') as Category;
  const step = stepData.value.getStep('START')!;
  try {
    const res = await process_update({
      cid: categoryId,
      data: step.format(),
      jobStep: 'SQL_EXECUTED',
      excelUrl: sqlData.value.uploadExcel || sqlData.value.genExcel,
    });
    if (res.code == 'ok') {
      result.value = '执行成功';
    } else {
      // message.error(res.message);
    }
  } catch (error) {
    console.log('%c Line:127 🍖 error', 'color:#2eafb0', error);
  }
  sqlLoaindg.value = false;
};

const router = useRouter();
const finish = () => {
  const { id: categoryId } = st.get('_category') as Category;
  router.push({
    path: `/category`,
    query: {
      categoryId,
    },
  });
};
</script>
